package br.com.wepa.webapps.orca.controle.exception;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.config.ExceptionConfig;

import br.com.wepa.webapps.logger.TraceLogger;
import br.com.wepa.webapps.orca.controle.ConstantesControle;
import br.com.wepa.webapps.orca.controle.ControleWeb;

public class ControlExceptionHandler extends ExceptionHandler implements ConstantesControle {

	private static TraceLogger logger = new TraceLogger(
			ControlExceptionHandler.class);

	@Override
	public ActionForward execute(Exception ex, ExceptionConfig exConfig,
			ActionMapping mapping, ActionForm formInstance,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException {
		logger.entering();

		if (ex instanceof SessaoExpiradaException) {
			return ControleWeb.newActionForward(GLOBAL_ACTION_SESSAOEXPIRADA);			
		}
		
		String msg = ex.getMessage();
		if (msg == null || msg.trim().equals("")) {
			Throwable cause = ex.getCause();
			if (cause != null) {
				msg = ex.getCause().toString();
			} else {
				msg = ex.toString();
			}
		}
		logger.error(msg, ex);

		request.setAttribute(CONTROL_EXCEPTION_MSG, msg);

		logger.exiting();
		return mapping.findForward(ConstantesControle.GLOBAL_FWPAGE_exibeMsg);
	}
}
